package es.sergionadal.mvc.dispatcher;

import java.util.HashMap;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import es.sergionadal.mvc.action.Action;
import es.sergionadal.mvc.action.exception.ActionException;
import es.sergionadal.mvc.dispatcher.exception.DispatcherException;

public abstract class AbstractDispatcher {

	private int resultado;

	

	private Activity activityOrigen;

	private Bundle bundle = null;

	public AbstractDispatcher(Activity activityOrigen, Bundle bundle,
			int resultado) {
		this.resultado = resultado;
		this.activityOrigen = activityOrigen;
		this.bundle = bundle;
	}

	public AbstractDispatcher(Activity activityOrigen, int resultado) {
		this.resultado = resultado;
		this.activityOrigen = activityOrigen;
	}

	protected abstract HashMap<Integer, Class<? extends Activity>> getDispatch();

	public Action getAction() {
		return new Action(this);
	}

	public void dispatch() throws DispatcherException {
		dispatch(new Intent(activityOrigen, getDispatch().get(resultado)), true);
	}

	public void dispatch(boolean finish) throws DispatcherException {
		dispatch(new Intent(activityOrigen, getDispatch().get(resultado)),
				finish);
	}

	public void dispatch(Intent intent, boolean finish)
			throws DispatcherException {
		try {
			getAction().run();
		} catch (ActionException e) {
			throw new DispatcherException(e.getMessage());

		}
		if (bundle != null)
			intent.putExtras(bundle);
		activityOrigen.startActivity(intent);

		if (finish)
			activityOrigen.finish();
	}

	public Activity getActivityOrigen() {
		return activityOrigen;
	}

	public Bundle getBundle() {
		return bundle;
	}

	public void setBundle(Bundle bundle) {
		if (this.bundle==null)
			this.bundle = bundle;
		else
			this.bundle.putAll(bundle);
	}
	
	public int getResultado() {
		return resultado;
	}

}
